<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import {snackbar} from './store'

// 查询
const itemsPerPage = ref(10);
const pageNo = ref(1);
const headers = [
    {title: '序号', key: 'num', sortable: false},
    {title: '企业名称', key: 'companyName', sortable: false},
    {title: '企业类型', key: 'companyType', sortable: false},
    // {title: '经度', key: 'bLon', sortable: false},
    // {title: '纬度', key: 'bLat', sortable: false},
    {title: '创建时间', key: 'createTime', sortable: false},
    {title: '操作', key: 'actions', sortable: false}
];
const companyList = ref([
    {value:'48',title:'党委机关'},
    {value:'50',title:'事业单位'},
    {value:'51',title:'电子政务'},
    {value:'52',title:'政府机关'},
    {value:'53',title:'大型国企'},
    {value:'54',title:'其他单位'}
]);
const delList = ref([
    { value: '1', title: '正常' },
    { value: '0', title: '已删除' }
])
const items = ref([]);
const loading = ref(true);
const totalItems = ref(0);

const search = ref('');
const name = ref(null);
const code = ref(null);
const delFlag = ref("1");
watch(name, () => {
    search.value = name.value
})
watch(code, () => {
    search.value = code.value
})
watch(delFlag, () => {
    search.value = delFlag.value
})


function loadItems({page, itemsPerPage}) {
    pageNo.value = page
    loading.value = true;
    axios.post('/companyDefend/select', {
        pageNo: pageNo.value,
        pageSize: itemsPerPage,
        delFlag: delFlag.value,
        companyName: name.value,
        companyType: code.value
    }).then(res => {
        items.value = res.data.records;
        totalItems.value = res.data.total;
        loading.value = false;
    })
}

onMounted(() => {});

// 增改
const isShowDialog = ref(false)
const dialogEnum = {
    update: '编辑',
    create: '新增'
}
const dialogType = ref(null)
const isShowDeleteDialog = ref(false)
const editedItem = ref({
    companyName: "",
    companyType: "",
    bLon: "",
    bLat: ""
});

function resetEditedItem() {
    editedItem.value = {
        companyName: "",
        companyType: "",
        bLon: "",
        bLat: ""
    }
}

function clickNew() {
    dialogType.value = dialogEnum.create
    isShowDialog.value = true
}

function close() {
    isShowDialog.value = false
    resetEditedItem()
    dialogType.value = null
}

function clickEdit(item) {
    editedItem.value = Object.assign({}, item)
    editedItem.value.status += ""
    editedItem.value.companyType += ""
    isShowDialog.value = true
    dialogType.value = dialogEnum.update
}

function save() {
    if (dialogType.value === dialogEnum.update) {
        axios({
            method: 'POST',
            url: '/companyDefend/update',
            data: editedItem.value
        }).then(() => {
            snackbar.info('编辑成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: itemsPerPage.value})
        })
    } else if (dialogType.value === dialogEnum.create) {
        axios({
            method: 'POST',
            url: '/companyDefend/save',
            data: editedItem.value
        }).then((res) => {
            console.log(res.data)
            snackbar.info('创建成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: itemsPerPage.value})
        })
    }
}

// 删
const beDeleteItem = ref({})
const delTrue = ref(false);

function clickDelete(item, type) {
    isShowDeleteDialog.value = true
    beDeleteItem.value = item
    delTrue.value = type
}

function clickDeleteConfirm() {
    if(!delTrue.value) {
        axios.post('/companyDefend/delete', {id: beDeleteItem.value.id}).then(() => {
            snackbar.info("删除成功")
            loadItems({page: pageNo.value, itemsPerPage: itemsPerPage.value})
            clickCloseDelete()
        })        
    } else {
        axios.post('/companyDefend/restore', {id: beDeleteItem.value.id}).then(() => {
            snackbar.info("恢复成功")
            loadItems({page: pageNo.value, itemsPerPage: itemsPerPage.value})
            clickCloseDelete()
        })   
    }
}

function clickCloseDelete() {
    isShowDeleteDialog.value = false
    beDeleteItem.value = null
}

const FileInput = ref(null);
const fileList = ref([]);
function clickUpload() {
    FileInput.value.click()
}

function clickDownloadWord() {
    console.log("尝试下载文件...");
    const attachmentUrl = "/defend_temp.xlsx";
    const link = document.createElement("a");
    link.href = attachmentUrl;
    link.download = "防守企业模板.xlsx";
    document.body.appendChild(link); // 很重要，添加到 DOM
    link.click();
    document.body.removeChild(link); // 下载完后移除
}

function uploadFile() {
    if(1) {
        var formData = new FormData();
        formData.append('file', fileList.value)
        axios({
            method: "POST",
            url: "/companyDefend/batchImport",
            data: formData,
            headers: {
                'Content-Type': "multipart/form-data"
            }
        }).then(res => {
            if(res.code == 200) {
                snackbar.info("上传成功")
            } else if(res.code == 500) {
                snackbar.info(res.message)
            }
        })
    }
}
</script>

<template>
    <v-toolbar density="compact">
        <v-toolbar-title>防守方企业管理</v-toolbar-title>
        <v-text-field v-model="name" :clearable="true" hide-details label="查询企业名称"></v-text-field>
        <v-select :items="companyList" v-model="code" :clearable="true" hide-details label="查询企业类型"></v-select>
        <v-select :items="delList" v-model="delFlag" hide-details label="企业状态"></v-select>
        <v-file-input label="File input" @change="uploadFile" v-model="fileList" ref="FileInput" v-show="false"></v-file-input>
        <v-dialog v-model="isShowDialog" max-width="500px">
            <template v-slot:activator="{ props }">
                <v-btn icon="mdi-plus" v-on:click="clickNew" v-bind="props"></v-btn>
            </template>
            <v-card>
                <v-card-title>{{ dialogType }}</v-card-title>
                <v-card-text>
                    <v-text-field v-model="editedItem.companyName" label="企业名称" required></v-text-field>
                    <v-select
                    :items=companyList
                    v-model="editedItem.companyType"
                    label="企业类型"
                    required></v-select>
                    <!-- <v-text-field v-model="editedItem.bLon" label="经度" required></v-text-field>
                    <v-text-field v-model="editedItem.bLat" label="纬度" required></v-text-field> -->
                </v-card-text>
                <v-card-actions>
                    <v-btn color="primary" variant="text" @click="close">关闭</v-btn>
                    <v-btn color="primary" variant="text" @click="save">确定</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-tooltip text="导入企业" location="bottom">
            <template v-slot:activator="{ props }">
                <v-btn icon="mdi-upload" v-on:click="clickUpload" v-bind="props"></v-btn>
            </template>
        </v-tooltip>
        <v-tooltip text="下载导入模板" location="bottom">
            <template v-slot:activator="{ props }">
                <v-btn icon="mdi-download" v-on:click="clickDownloadWord" v-bind="props"></v-btn>
            </template>
        </v-tooltip>
        <v-dialog v-model="isShowDeleteDialog" max-width="500px">
            <v-card>
                <v-card-title class="text-h5">确定{{ delTrue ? '恢复' : '删除' }}该企业?</v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue-darken-1" variant="text" @click="clickCloseDelete">取消</v-btn>
                    <v-btn color="blue-darken-1" variant="text" @click="clickDeleteConfirm">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-toolbar>
  <!--  分页文本待更换   items-per-page-text="每页数量"-->
    <v-data-table-server :search="search" :items-per-page="itemsPerPage" :headers="headers" :items-length="totalItems"
    :items="items"
    :loading="loading"
    class="elevation-1"
    items-per-page-text="每页数量"
    @update:options="loadItems">
        <template v-slot:item.num="{ index }">
            <span>{{ index + 1 }}</span>
        </template>
        <template v-slot:item.companyType="{ item }">
            <span v-for="k in companyList" v-show="k.value == item.companyType">
                {{ k.title }}
            </span>
        </template>
        <template v-slot:item.status="{ item }">
            <v-chip v-if="item.status == 0" color="green">
                正常
            </v-chip>
            <v-chip v-if="item.status == 1" color="red">
                停用
            </v-chip>
        </template>
        <template v-slot:item.actions="{ item }">
            <v-btn icon="mdi-pencil" variant="text" @click="clickEdit(item, false)"></v-btn>
            <v-btn icon="mdi-delete" v-if="item.delFlag" variant="text" @click="clickDelete(item)"></v-btn>
            <v-btn icon="mdi-reload" v-else variant="text" @click="clickDelete(item, true)"></v-btn>
        </template>
    </v-data-table-server>
</template>

<style scoped lang="less">

</style>
